<?php
namespace control;
// 计提折旧
class assetDepreciationClass extends adIndexClass
{
    private const page = 'assetDepreciation';         # 权限
    private const table = 'asset_depreciation';        # 数据表
    private const tableMx = 'asset_depreciation_detail'; # 子表
    private const title = '计提折旧';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "单据编号",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'month'  => [
                        'name'  => '计提期间',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'stid'         => [
                        'name'  => '制单人',
                        'width' => 300,
                    ],
                    'recordDate'          => [
                        'name'  => '盘点日期',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 300,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "盘点名称" => text(array("name" => "name")),
                    "制单人" => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name']),
                ],
                [
                    "计提期间" => text(
                        [
                            'name' => 'date',
                            'laydate' => ['range' => '~', 'type' => 'date'],
                        ]
                    ),
                    "单据日期" => text(
                        [
                            'name' => 'recordDate',
                            'laydate' => ['range' => '~', 'type' => 'date'],
                        ]
                    ),
                    "状态" => select(["name" => "state", 'option' => ['制单', '审核中', '已通过']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*固定资产入口页*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $root = $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editPage&acid=' . $this->post('objId');
            $button .= "
			<span class='spanButton' onclick=\"newIframe('新建盘点','" . $root . "')\">新增</span>";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "export")) {
            $button .= "<a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportAll' class='spanButton'>导出</a>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*固定资产列表*/
    public function homeSearch()
    {
        //查询结果
        $where = ' 1=1 ';
        $equal = [
            'month' => $this->post('date'),
            'coid' => self::$coid,
        ];
        $like = [
            'orderNo' => $this->post('orderNo'),
            'stid' => $this->post('stid'),
            'state' => $this->post('state'),
        ];
        //生成查询语句

        $where .= search([
            "=" => $equal,
            "like" => $like,
        ]);
        if ($this->post('recordDate')) {
            $where .= self::timeComparison($this->post('recordDate'), 'date', 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => ["name" => "listId", "value" => $array['id']],
                "edit" => $array['state'] == '制单' ? ["title" => self::title, "click" => "newIframe('" . self::title . "','" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=editPage&id=" . $array['id'] . "')"] : [],
                "detail" => ["title" => self::title, "click" => "newIframe('" . self::title . "','" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $array['id'] . "')"],
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'stid':
                        $row[] = self::findStaff($array['stid']);
                        break;
                    case 'recordDate':
                        $row[] = self::formatDate($array['recordDate']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    public function editPage()
    {
        $id = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        $button[] = [
            "name" => "保存",
            "type" => "点击事件",
            "fun" => "subForm('" . self::page . "EditPageForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editPageEdit')",
            'style' => 'li-btn-blue-bg',
        ];
        $endDate = $info['id']?($info['month'].'-'.sprintf('%02d',date('t',strtotime($info['month'])))):$this->date;
        $tr[] = ['', '固定资产编码', '名称', '品牌', '规格型号', '计量单位', '数量', '使用部门', '折旧年限', '资产原值','期初累计折旧','预计净残值','本月折旧','月折旧率','期末累计折旧','期末剩余计提'];
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
        foreach ($result['array'] as $k=>$array) {
            $asset = query('asset', " id = '{$array['atid']}' ");
            $ratio = assetManagementClass::monthRatio($asset['depreciationMethod'],$asset['discountYear'],$asset['money'],$asset['purchaseMoney'],$asset['depreciationMoney'],$asset['purchaseDate'],$endDate,1);
            $monthDecMoney =assetManagementClass::monthDecMoney($asset['depreciationMethod'],$asset['purchaseMoney'],$ratio/100,$asset['purchaseDate'],$endDate,$asset['discountYear'],$asset['money'],$asset['depreciationMoney']);
            $discountMoney = assetManagementClass::calcSalvage($asset['depreciationMethod'],$monthDecMoney,$asset['purchaseDate'],$asset['discountYear'],$asset['purchaseMoney'],$asset['money'],$asset['depreciationMoney'],$endDate);

            $tr[] = [
                componentClass::tablePperation($k+1,"delTableRow(this)").
                hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                hidden(array('name' => 'atid[]', 'value' => $array['atid'])),
                $asset['orderNo'],
                $asset['name'],
                $asset['brand'],
                $asset['model'],
                $asset['unit'],
                $asset['num'],
                departmentClass::getTypeName($asset['departmentId']),
                $asset['discountYear'],
                $asset['purchaseMoney'],
                assetManagementClass::calcSalvage($asset['depreciationMethod'],$monthDecMoney,$asset['purchaseDate'],$asset['discountYear'],$asset['purchaseMoney'],$asset['money'],$asset['depreciationMoney'],date('Y-m-d',strtotime("-1 month",strtotime($endDate)))),
                $asset['money'],
                $monthDecMoney,
                $ratio.'%',
                $discountMoney,
                round($asset['purchaseMoney']-$discountMoney-$asset['money'],2)
            ];
        }
        $list = $this->listTable(array('tr' => $tr, 'end' => true));
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . '计提期间' => text(['name' => "month", 'class' => 'text', 'laydate' => ['type' => 'month'], 'value' => $info['month']?:date('Y-m')]),
                    must . '单据日期' => text(['name' => "recordDate", 'class' => 'text', 'laydate' => [], 'value' => $info['recordDate'] ?: $this->date]),
                ],
                [
                    '备注' => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '明细',
            'button' => "<span class='smallButton' onclick=\"getInventory()\">获取明细</span>",
            'html' => $list,
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(array('name' => 'id', 'value' => $id)),
        ]);
        $data['html'] .= $this->js();
        //返回
        return $this->tab($data);
    }

    /**
     * JS
     * @return string
     */
    public function js(): string
    {
        return <<<eof
<script>
function getInventory(){
         $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getInventory',$("form[name='assetDepreciationEditPageForm']").serialize(),function(res) {
             if (res.warn ==2){
                $("#materialTable tbody").empty().append(res.html);
                resetNumber($("#materialTable tbody"))
           }else{
               msg(res.warn,'error');
           }
            
        },'json');
}

</script>
eof;

    }

    /*基本资料新增或修改-异步处理*/
    public function editPageEdit()
    {
        $mxIdArr = $this->post('mxId')?:[];
        $atidArr = $this->post('atid');
        $id = $this->post('id') ?: self::getId();
        $field = [
            'recordDate' => $this->post('recordDate'),
            'month' => $this->post('month'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'month' => '计提期间',
            'recordDate' => '单据日期',
            'text' => '备注',
        ];
        $rules = [
            'month' => 'required',
            'recordDate' => 'required|date',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif ($info['id'] && $info['state'] != '制单') {
            $json['warn'] = '此单据不是制单状态，不能编辑';
        }elseif(static::total(array('table'=>self::table,'where'=>"month = '$field[month]' and coid = '".self::$coid."' and id !='$id'")) >0){
            $json['warn'] = '已存在此计提期间的单据';
        } else {
            $this->startTrans();
            if (!$info['id']) {
                $orderNo = codeTemplateClass::generateCode(self::page, [
                    'table' => self::table,
                    'prefix' => 'JTZJ' . date('Ymd'),
                    'default' => '001',
                ], $field);
                $field = array_merge($field, [
                    'id' => $id,
                    'coid' => self::$coid,
                    'orderNo' => $orderNo,
                    'state' => '制单',
                    'stid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            foreach ($mxIdArr as $k => $nid) {
                $mx = query(self::tableMx, "id = '$nid'");
                if (!empty($mx['id'])) {
                    //更新
                    $warn = static::update([
                        "table" => self::tableMx,
                        "field" => [
                            'atid' => $atidArr[$k],
                        ],
                        "where" => " id = '$nid'"
                    ]);
                } else {
                    //新增
                    $warn = static::insert([
                        "table" => self::tableMx,
                        "field" => [
                            'id' => $nid,
                            'orderId' => $id,
                            'coid' => self::$coid,
                            'atid' => $atidArr[$k],
                        ],

                    ]);
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $json['warn'] = $warn;
                    break;
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】,单据编号：【'.$info['id']?$info['orderNo']:$field['orderNo'].'】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 审核按钮
     *
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
        if ($info['state'] == '制单' || auditClass::auditFlag(self::table, $info['id'], 'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => [
                    "act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'name' => '计提折旧',
                        'table' => self::table,
                        'process' => [
                            // 预览函数
                            'detail' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'detail',
                            ],
                            // 保存函数
                            'save' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'editPageEdit',
                            ],
                            //执行发起时验证函数
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        // 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => [
                    "act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                        // 当前状态
                        'state' => $info['state'],
                        // 变更
                        'field' => ['state'],   //变更字段 可多个
                        'value' => [
                            'state' => ['制单', '已通过'],
                        ],
                        // 审核时回调
                        'process' => [
                            //执行首次审核时验证
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //执行末次审核后处理
                            'after' => [
                                'cla' => $this->get('cla'),
                            ],
                        ],
                    ], 320)),
                ],
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];

        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] == '审核中') {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                        // 当前状态
                        'state' => $info['state'],
                        // 变更
                        'field' => ['state'],   //变更字段 可多个
                        'value' => [
                            'state' => ['制单'],
                        ],
                        'process' => [
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
								'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        return $button;
    }

    public function detail()
    {
        $info = query(self::table, " id = '" . $this->get('id') . "' ");
        if (!$this->power(self::page, "see")) {
            $html = "你没有查看权限";
        } elseif (!$this->get('id')) {
            $html = "ID为空";
        } elseif (!$info['id']) {
            $html = "未找到此信息";
        } else {
            $data = [
                "id" => $info['id'],
            ];
            //按钮
            $button = [];
            $button = array_merge($button, $this->auditButton($info));
            if ($info['state'] == '制单') {
                if ($this->power(self::page, "edit")) {
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => "编辑用户",
                        "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editPage&id=' . $info['id'],
                    ];
                }
                if ($this->power(self::page, "del")) {
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }

            $initDepreciation =$monthDepreciation=$endDepreciation=$remindDepreciation= 0;

            // 子表
            $mxtr[] = ['固定资产编码', '名称', '品牌', '规格型号', '计量单位', '数量', '使用部门', '折旧年限(月)', '资产原值','期初累计折旧','预计净残值','本月折旧','月折旧率','期末累计折旧','期末剩余计提'];
            if ($info['id']) {
                $endDate = $info['month'].'-'.sprintf('%02d',date('t',strtotime($info['month'])));
                //订单明细
                $all = self::sqlFind("SELECT * FROM " . self::tableMx . " WHERE orderId = '$info[id]' ORDER BY list ");
                foreach ($all as $array) {
                    $asset = query('asset', " id = '{$array['atid']}' ");
                    $ratio = assetManagementClass::monthRatio($asset['depreciationMethod'],$asset['discountYear'],$asset['money'],$asset['purchaseMoney'],$asset['depreciationMoney'],$asset['purchaseDate'],$endDate,1);
                    $monthDecMoney =assetManagementClass::monthDecMoney($asset['depreciationMethod'],$asset['purchaseMoney'],$ratio/100,$asset['purchaseDate'],$endDate,$asset['discountYear'],$asset['money'],$asset['depreciationMoney']);
                    $discountMoney = assetManagementClass::calcSalvage($asset['depreciationMethod'],$monthDecMoney,$asset['purchaseDate'],$asset['discountYear'],$asset['purchaseMoney'],$asset['money'],$asset['depreciationMoney'],$endDate);
                    $initMoney = assetManagementClass::calcSalvage($asset['depreciationMethod'],$monthDecMoney,$asset['purchaseDate'],$asset['discountYear'],$asset['purchaseMoney'],$asset['money'],date('Y-m-d',strtotime("-1 month",strtotime($endDate))));
                    $initDepreciation+=$initMoney;
                    $monthDepreciation+=$monthDecMoney;
                    $endDepreciation+=$discountMoney;
                    $remindDepreciation+=round($asset['purchaseMoney']-$discountMoney-$asset['money'],2);
                    $mxtr[] = [
                        $asset['orderNo'],
                        $asset['name'],
                        $asset['brand'],
                        $asset['model'],
                        $asset['unit'],
                        $asset['num'],
                        departmentClass::getTypeName($asset['departmentId']),
                        $asset['discountYear'],
                        $asset['purchaseMoney'],
                        $initMoney,
                        $asset['money'],
                        $monthDecMoney,
                        $ratio.'%',
                        $discountMoney,
                        round($asset['purchaseMoney']-$discountMoney-$asset['money'],2)
                    ];
                }
            }
            $total_tr = [
                    14=>$remindDepreciation,
                    13=>$endDepreciation,
                    11=>$monthDepreciation,
                    9=>$initDepreciation
                ];
            $detailHtml = $this->listTable(['tr' => $mxtr, 'total' => $total_tr, 'showSort' => true]);
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow([
                [
                    [
                        "单据编号" => $info['orderNo'],
                        "计提期间" => $info['month'],
                        "单据日期" => $info['recordDate'],
                        "制单人" => self::findStaff($info['stid']),
                    ],
                    [
                        "状态" => $info['state'],
                    ],
                    [
                        "备注" => pre($info['text']),
                    ],
                ],
            ]);
            $data['html'] .= $this->detailList([
                'title' => '明细',
                'html' => $detailHtml,
            ]);
            $data['html'] .= $this->detailBlock([
                '流程' => auditClass::auditRecord(self::table, $info['id'])
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }




    /**
     * 导入所有
     */
    public function getInventory(): bool|string
    {
        $month = $this->post('month');
        if (empty($month)){
            $json['warn'] = '请先选择计提期间';
        }else{
            $endDate = $month.'-'.sprintf('%02d',date('t',strtotime($month)));
            $result = find([
                'table' => 'asset',
                'where' => "state != '已处置' and coid = '" . self::$coid . "' and depreciationMethod !='不折旧'" ,
            ]);
            $tr = [];
            foreach ((array)$result['array'] as $value) {
                $ratio = assetManagementClass::monthRatio($value['depreciationMethod'],$value['discountYear'],$value['money'],$value['purchaseMoney'],$value['depreciationMoney'],$value['purchaseDate'],$endDate,1);
                $monthDecMoney =assetManagementClass::monthDecMoney($value['depreciationMethod'],$value['purchaseMoney'],$ratio/100,$value['purchaseDate'],$endDate,$value['discountYear'],$value['money'],$value['depreciationMoney']);
                $discountMoney = assetManagementClass::calcSalvage($value['depreciationMethod'],$monthDecMoney,$value['purchaseDate'],$value['discountYear'],$value['purchaseMoney'],$value['money'],$value['depreciationMoney'],$endDate);
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this)").
                    hidden(array('name' => 'mxId[]', 'value' => suiji())) .
                    hidden(array('name' => 'atid[]', 'value' => $value['id'])),
                    $value['orderNo'],
                    $value['name'],
                    $value['brand'],
                    $value['model'],
                    $value['unit'],
                    $value['num'],
                    departmentClass::getTypeName($value['departmentId']),
                    $value['discountYear'],
                    $value['purchaseMoney'],
                    assetManagementClass::calcSalvage($value['depreciationMethod'],$monthDecMoney,$value['purchaseDate'],$value['discountYear'],$value['purchaseMoney'],$value['money'],$value['depreciationMoney'],date('Y-m-d',strtotime("-1 month",strtotime($endDate)))),
                    $value['money'],
                    $monthDecMoney,
                    $ratio.'%',
                    $discountMoney,
                    round($value['purchaseMoney']-$discountMoney,2)
                ];
            }
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false, 'end' => false]);
            $json['warn'] = 2;
        }

        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = $word = '';
        $append = [];
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'isDelete';
                $form = self::page . 'OperateForm, listForm';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'append' => $append,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    // 确认删除信息
    public function isDelete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除" . self::title . "的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一条记录都没有选择呢";
        } else {
            $text = '';
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            // 判断field
            foreach ($array as $id) {
                $where = " id = '$id' ";
                $info = query(self::table, $where);
                if ($info['state'] != '制单') {
                    //添加记录
                    $text .= "{$this->control['name']}删除" . self::title . "：ID【{$id}】,编号【{$info['orderNo']}】失败：不是制单状态<br>";
                } else {
                    // 删除子表
                    delete([
                        "table" => self::table . 'Mx',
                        "where" => " orderId = '$id' ",
                    ]);
                    // 删除表
                    delete([
                        "table" => self::table,
                        "where" => $where,
                    ]);
                    //删除audit表记录
                    delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message", "where" => " typeId = '$id' "));
                    //添加记录
                    $text .= "{$this->control['name']}删除了一条" . self::title . "：ID【{$id}】,编号【{$info['orderNo']}】<br>";
                    $x++;
                }
            }

            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = "删除了{$x}条" . self::title;
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }

        resp:
        return json_encode($json, 320);
    }


}
